<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule\AclModule;

use Albireo\Forms\AlbireoForm;
use Nette\Application\AppForm;
use Nette\Forms\Form;
use \dibi;

/**
 * Privileges presenter
 *
 * @inherits cancelClicked() from Kernel\Acl\BasePresenter
 * @inherits createComponentPaginator() from Kernel\Acl\BasePresenter
 * @inherits addFormButtons from Kernel\Acl\BasePresenter
 * @inherits createComponentDelete() from Kernel\Acl\BasePresenter
 *
 * @extends \Kernel\Acl\BasePresenter
 * @author Pavel
 */
class PrivilegesPresenter extends BasePresenter {
    
    /** @var AclManagment */
    private $aclManager;

    /**
     * Lazy getter for AclManagement
     * @return AclManagement
     */
    private function getAclManager() {
        if ($this->aclManager === NULL) {
            $this->aclManager = new AclManagement();
        }
        return $this->aclManager;
    }


     public function renderDefault($search) {
        $this->search = $search;

        $this->template->title = _("Privileges Management");
        $this->template->search = $search;

        $this->bringPrivileges($search);
    }

    public function handleDefault($search) {
        $this->bringPrivileges($search);
        $this->invalidateControl("list");
    }

    private function bringPrivileges($search) {
        $form = $this->getComponent('search');
        $form->setDefaults(array("privilege" => $this->search));

        $paginator = $this->getComponent("paginator")->getPaginator();

        $usersDataSource = $this->getAclManager()->getSearchDataSource("privileges", $this->search);

        $paginator->itemCount = $usersDataSource->count();
        $usersDataSource->applyLimit($paginator->itemsPerPage, $paginator->offset);

        $this->template->privileges = $usersDataSource;
    }
    
    public function actionAdd() {
        $this->template->title = _("Add New Privilege");
        $this->view = "addOrEdit";
    }
    
    public function actionEdit($id) {
        $this->template->title = _("Edit Privilege");
        $this->view = "addOrEdit";

        $privilege = $this->getAclManager()->getPrivilegeById($id);
        //TODO HANDLE exception here
        if ($privilege == null) throw new \InvalidStateException();

        $default = array(
            "id" => $privilege->getId(),
            "name" => $privilege->getName(),
        );

        $this->template->privilegeName = $privilege->getName();

        $form = $this->getComponent('addEdit');
        $form->setDefaults($default);
    }
    
    protected function createComponentAddEdit() {
        $form = new AlbireoForm();
        $form->addText('name', _('Privilege name'), 30)
            ->addRule(Form::FILLED, _("Please, enter the privilege name"));

        $this->addFormButtons($form);

        return $form;
    }
    
    public function addOrEditSubmitted(AlbireoForm $form) {

        $values = $form->getValues();

        $newPrivilege = new AclPrivilege();
        $newPrivilege->setName($values["name"]);

        if ($this->getAction() == "add") {
            if ($this->getAclManager()->addPrivilege($newPrivilege)) {
                $this->flashMessage(_('The privilege has been added.'), 'ok');
            } else {
                $this->flashMessage(_("The privilege cannot be added, possibly it already exists."), 'error');
            }
        } elseif($this->getAction() == "edit") {
            $newPrivilege->setId($values["id"]);
            if ($this->getAclManager()->updatePrivilege($newPrivilege)) {
                $this->flashMessage(_('The privilege has been edited.'), 'ok');
            } else {
                $this->flashMessage(_("The privilege description can't be updated."), 'error');
            }
        } else throw new \InvalidStateException(); //this should never happen
        $this->redirect("default");
    }

    public function actionDelete($id) {
        $deletedPrivilege = $this->getAclManager()->getPrivilegeById($id);
        if ($deletedPrivilege == NULL) {
            $this->flashMessage(_("The privilege doesn't exist."), "error");
            $this->redirect('default');
        }
        $this->template->title = _("Delete Privilege");
        $this->template->name = $deletedPrivilege->getName();
        $this["delete"]->setDefaults(array("id" => $deletedPrivilege->getId()));
    }

    public function deleteOnFormSubmitted(AppForm $form){
        if ($form['delete']->isSubmittedBy()) {
            $values = $form->getValues();
            $deletedPrivilege = $this->getAclManager()->getPrivilegeById($values["id"]);
            if ($this->getAclManager()->deleteFromAcl($deletedPrivilege)) {
                $this->flashMessage(_('The privilege has been deleted succesfuly.'), 'ok');
            } else $this->flashMessage(_("The privilege has not been deleted."), "error");
        }
        $this->redirect("default");
    }


    protected function createComponentSearch($name) {
        return $this->createSearchForm($name, _("privilege"));
    }

    public function searchSubmitted(AppForm $form) {
        $values = $form->getValues();
        $this->search = $values["searchinput"];
        $this->redirect("default");
    }

}